package com.lhcai.lc.category.designsimulate;

/**
 * 2296. 设计一个文本编辑器
 *
 * @author liuhuaicai
 * @since 2024-11-10 16:48
 */
public class TextEditor {
    public static void main(String[] args) {
        TextEditor textEditor = new TextEditor();
        textEditor.addText("cyberworks");
        textEditor.deleteText(21);
        textEditor.cursorLeft(2);
        textEditor.cursorRight(6);
        textEditor.addText("aaaaa");
        textEditor.cursorLeft(1);
    }

    int index;
    StringBuilder sb;

    public TextEditor() {
        index = 0;
        sb = new StringBuilder();
    }

    public void addText(String text) {
        sb.insert(index, text);
        index += text.length();
    }

    public int deleteText(int k) {
        if (k > index) {
            k = index;
            sb.delete(0, k);
            index = 0;
            return k;
        }
        sb.delete(index - k, index);
        index = index - k;
        return k;
    }

    public String cursorLeft(int k) {
        if (k > index) {
            index = 0;
            return "";
        }
        index -= k;
        int cur = Math.min(10, index);
        return sb.substring(index - cur, index);
    }

    public String cursorRight(int k) {
        if (k + index > sb.length()) {
            index = sb.length();
            int start = Math.max((sb.length() - 10), 0);
            return sb.substring(start, sb.length());
        }
        index += k;
        int cur = Math.min(10, index);
        return sb.substring(index - cur, index);
    }
}
